#!/usr/bin/env python
# -*- coding:utf-8 -*-

import re
import argparse
import subprocess
import os
import commands
import time
import uuid
import MySQLdb
import ConfigParser

VERSION = "1.0.1"


def create_fastdfs_list(all_tracker_ip):
    """
    生成修改fdfs.tracker-list命令
    :param all_tracker_ip: 部署的服务节点
    :return:
    """
    fastdfs_list_ips = ','.join(["{ip}:22122".format(ip=ip) for ip in all_tracker_ip])
    cmd = "sed -i '/^fdfs.tracker-list/c fdfs.tracker-list={fastdfs_list_ips}' application.properties". \
        format(fastdfs_list_ips=fastdfs_list_ips)
    return cmd


def create_fastdfs_web_server(all_tracker_ip):
    """
    生成修改fdfs.web-server-url命令
    :param all_ip: 部署的服务节点
    :return:
    """
    fastdfs_list_ips = ','.join(["{ip}:88".format(ip=ip) for ip in all_tracker_ip])
    cmd = "sed -i '/^fdfs.web-server-url/c fdfs.web-server-url={fastdfs_list_ips}' application.properties". \
        format(fastdfs_list_ips=fastdfs_list_ips)
    return cmd


def create_ip_address(net_ip):
    """
    生成修改eureka.instance.ip-address=127.0.0.1
            spring.cloud.inetutils.preferred-networks=127.0.0.1
            这两项配置的命令
    :param net_ip: 部署服务的节点
    :return:
    """
    if net_ip != "127.0.0.1":
        cmd = "sed -i '/^spring.cloud.inetutils.preferred-networks/d' application.properties && " \
              "sed -i '$a spring.cloud.inetutils.preferred-networks={net_ip}' application.properties". \
            format(net_ip=net_ip)
    else:
        cmd = "sed -i '/^spring.cloud.inetutils.preferred-networks/d' application.properties".format(net_ip=net_ip)
    return cmd


def exec_cmd(cmd, block=False, cwd=None):
    p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=cwd, shell=True)
    if block:
        p.wait()
    out = p.stdout
    err = p.stderr
    returncode = p.returncode
    print "{returncode}:{cmd}".format(returncode=returncode, cmd=cmd)
    return out, err, returncode


def create_eureka_ip_cmd(all_ip):
    """
    生成修改eureka_ip命令
    :param all_ip: 部署的服务节点
    :return:
    """
    eureka_ips = ','.join(["http://{ip}:8010/eureka/".format(ip=ip) for ip in all_ip])
    cmd = "sed -i '/^eureka.client.serviceUrl.defaultZone/c eureka.client.serviceUrl.defaultZone={eureka_ips}' application.properties". \
        format(eureka_ips=eureka_ips)
    return cmd


def create_db_ip_cmd(database_ip):
    """
    生成修改database_ip命令
    :param database_ip: 数据库服务器地址
    :return:
    """
    cmd1 = "sed -i '/^spring.datasource.url/c spring.datasource.url=jdbc:mysql://{database_ip}:3306/cloud?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai&useSSL=false' application.properties". \
        format(database_ip=database_ip)
    cmd2 = "sed -i '/^mysql.addr/c mysql.addr={database_ip}' application.properties". \
        format(database_ip=database_ip)
    return [cmd1,cmd2]


def create_mq_ip_cmd(rabbitmq_ip):
    """
    生成修改rabbitmq_ip命令
    :param rabbitmq_ip: rabbitmq服务器地址
    :return:
    """
    cmd = "sed -i '/^spring.rabbitmq.host/c spring.rabbitmq.host={rabbitmq_ip}' application.properties". \
        format(rabbitmq_ip=rabbitmq_ip)
    return cmd


def create_redis_ip_cmd(redis_ip):
    """
    生成修改redis_ip命令
    :param redis_ip: redis_ip服务器地址
    :return:
    """
    cmd = "sed -i '/^spring.redis.host/c spring.redis.host={redis_ip}' application.properties". \
        format(redis_ip=redis_ip)
    return cmd


def create_gateway_ip_cmd(gateway_ip, gateway_port):
    """
    生成修改gateway_ip命令
    :param gateway_ip: 网关地址
    :return:
    """
    cmd1 = "sed -i '/^vcloud.gateway.ip/c vcloud.gateway.ip = {gateway_ip}' application.properties".\
        format(gateway_ip=gateway_ip)
    cmd2 = "sed -i '/^vcloud.gateway.port/c vcloud.gateway.port = {gateway_port}' application.properties".\
        format(gateway_port=gateway_port)
    return [cmd1, cmd2]


def create_vcfs_path_cmd(vcfs_path):
    """
    生成vcfs路径
    :param vcfs_path:vcfs路径
    :return:
    """
    cmd = "sed -i '/^diskMountPath=/c diskMountPath={}' application.properties".format(vcfs_path)
    return cmd


def deploy_keepalived(args):
    """
    修改keepalived配置信息
    :return:
    """

    try:
        # 获取命令行参数
        state = args.ks
        interface = args.ki
        vip = args.kv
        kpa_type = args.ha
        mask = args.ms
        gateway = args.gw

        state_val = "MASTER" if int(state) else "BACKUP"
        priority = "100" if int(state) else "90"
        vips = vip.replace(',', "\\n        ")

        print 'state :\033[1;32m %s \033[0m' % state_val if state_val else 'state : None'
        print 'priority :\033[1;32m %s \033[0m' % priority if priority else 'priority : None'
        print 'virtual_ipaddress :\033[1;32m %s \033[0m' % vip if vip else 'virtual_ipaddress : None'
        print 'high availability type :\033[1;32m %s \033[0m' % kpa_type if kpa_type else 'high availability type : None'
        print 'mask :\033[1;32m %d \033[0m' % mask
        print 'gateway :\033[1;32m %s \033[0m' % gateway

        line = commands.getstatusoutput("sed -n '/^vrrp_instance VI_%s/'p /etc/keepalived/keepalived.conf" % kpa_type)[
            1]

        if not line:
            if kpa_type:
                # 配置nginx
                if kpa_type == "nginx":
                    kpa_conf(state_val, interface, priority, vips, mask, gateway, kpa_type, "80")
                # 配置mysql
                elif kpa_type == "mysql":
                    kpa_conf(state_val, interface, priority, vips, mask, gateway, kpa_type, "81")
                # 配置redis
                elif kpa_type == "redis":
                    kpa_conf(state_val, interface, priority, vips, mask, gateway, kpa_type, "82")
                # 配置mq
                elif kpa_type == "mq":
                    kpa_conf(state_val, interface, priority, vips, mask, gateway, kpa_type, "83")
            else:
                kpa_conf(state_val, interface, priority, vips, mask)

        else:
            # 修改keepalived配置，根据高可用服务类型修改，只可修state,interface, 虚拟ip只能新增
            cmds = []
            if state_val:
                cmd = "sed -i '/^    state/c \\    state {state}' keepalived.conf".format(state=state_val)
                cmds.append(cmd)
                cmd = "sed -i '/^    priority/c \\    priority {priority}' keepalived.conf".format(
                    priority=priority)
                cmds.append(cmd)

            if interface:
                cmd = "sed -i '/^    interface/c \\    interface {interface}' keepalived.conf".format(
                    interface=interface)
                cmds.append(cmd)
            if vips:
                cmd = "sed -i '/^    virtual_ipaddress/a\\        {vips}' keepalived.conf".format(vips=vips)
                cmds.append(cmd)

            cmd = "systemctl restart keepalived"
            cmds.append(cmd)
            cmd = "systemctl enable keepalived"
            cmds.append(cmd)

            for cmd in cmds:
                exec_cmd(cmd, block=True, cwd="/etc/keepalived/")

    except Exception as err:
        print 'error =\033[1;31m %s \033[0m' % err


def kpa_conf(state_val, interface, priority, vips, mask, gateway="", check_type='', router_id="51",):

    try:
        if check_type:
            # 检查脚本文件是否存在
            check_sh_path = "/etc/keepalived/check_{check_type}.sh".format(check_type=check_type)
            if os.path.exists(check_sh_path):
                os.remove(check_sh_path)

            if check_type == "nginx" or check_type == "mysql":
                # 创建脚本文件
                # 生成监控脚本
                _conf = "#!/bin/bash" \
                        "\ncount=$(ps aux | grep ^{check_type} | wc -l)" \
                        "\nif [ $count != '0' ]; then" \
                        "\n    exit 0" \
                        "\nelse" \
                        "\n    exit 1" \
                        "\nfi".format(check_type=check_type)
                with open(check_sh_path, "w+") as f:
                    f.write(_conf)

            elif check_type == "redis":
                _conf = "#!/bin/bash\n" \
                        "status=$(/usr/bin/redis-cli -a cloud info replication | grep role: | " \
                        "awk -F \":\" '{print $2}' | awk -F \"\\r\" '{print $1}')\n" \
                        "if [ $status ]; then\n" \
                        "    if [ $status = 'master' ]; then\n" \
                        "        exit 0\n" \
                        "    else\n" \
                        "        exit 1\n" \
                        "    fi\n" \
                        "else\n" \
                        "    exit 1\n" \
                        "fi"
                with open(check_sh_path, "w") as f:
                    f.write(_conf)

            script = "sed -n '/^vrrp_script chk_%s {/'p /etc/keepalived/keepalived.conf" % check_type
            script_name = commands.getstatusoutput(script)[1]
            if not script_name:
                arping = '/usr/sbin/arping -I %s -c 5 -s %s %s &>/dev/null'%(interface, vips, gateway)
                notify_master = 'notify_master "/usr/bin/sh /etc/keepalived/redis_role_switch.sh"' if check_type == "redis" \
                    else 'notify_master "%s"' % arping
                if check_type == "redis" and os.path.exists("/etc/keepalived/redis_role_switch.sh"):
                    cmd = "sed -i '2 i\%s' /etc/keepalived/redis_role_switch.sh" % arping
                    exec_cmd(cmd, block=True, cwd="/etc/keepalived/")
                # 生成cmd信息
                # 写入keepalived配置
                chk_script = "/usr/bin/sh /etc/keepalived/check_{check_type}.sh >/dev/null 2>&1".format(
                    check_type=check_type)
                track_script = "chk_{check_type}".format(check_type=check_type)
                if check_type == "mq":
                    chk_script = "rabbitmqctl status"
                cmds = []
                if os.path.exists("/etc/keepalived/keepalived.conf"):
                    # keepalived 配置信息
                    conf = "vrrp_instance VI_%s {" \
                           "\\n    state %s" \
                           "\\n    interface %s" \
                           "\\n    virtual_router_id %s" \
                           "\\n    priority %s" \
                           "\\n    advert_int 1" \
                           "\\n    authentication {" \
                           "\\n        auth_type PASS" \
                           "\\n        auth_pass 1111" \
                           "\\n    }" \
                           "\\n    virtual_ipaddress {" \
                           "\\n        %s/%s" \
                           "\\n    }" \
                           "\\n    track_script {" \
                           "\\n        %s" \
                           "\\n    }" \
                           "\\n    %s" \
                           "\\n}" % \
                           (check_type.upper(), state_val, interface, router_id, priority, vips, mask, track_script,
                            notify_master)

                    cmd = "sed -i '$a\{conf}' keepalived.conf".format(conf=conf)
                    cmds.append(cmd)

                    conf = 'vrrp_script chk_%s {' \
                           '\\n    script "%s"' \
                           '\\n    interval 3' \
                           '\\n    weight -20' \
                           '\\n    fall 2' \
                           '\\n    rise 2' \
                           '\\n}' % (check_type, chk_script)

                    cmd = "sed -i '1a\{conf}' keepalived.conf".format(conf=conf)
                    cmds.append(cmd)

                    cmd = "systemctl restart keepalived"
                    cmds.append(cmd)
                    cmd = "systemctl enable keepalived"
                    cmds.append(cmd)

                for cmd in cmds:
                    exec_cmd(cmd, block=True, cwd="/etc/keepalived/")

                print '\033[1;32m finish \033[0m'
        else:
            conf = "vrrp_instance VI_1 {" \
                   "\\n    state %s" \
                   "\\n    interface %s" \
                   "\\n    virtual_router_id 51" \
                   "\\n    priority %s" \
                   "\\n    advert_int 1" \
                   "\\n    authentication {" \
                   "\\n        auth_type PASS" \
                   "\\n        auth_pass 1111" \
                   "\\n    }" \
                   "\\n    virtual_ipaddress {" \
                   "\\n        %s/%s" \
                   "\\n    }" \
                   "\\n    track_script {" \
                   "\\n    }" \
                   "\\n}" % (state_val, interface, priority, vips, mask)

            # 生成cmd信息
            cmds = []

            cmd = "sed -i '$a\{conf}' keepalived.conf".format(conf=conf)
            cmds.append(cmd)

            cmd = "systemctl restart keepalived"
            cmds.append(cmd)
            cmd = "systemctl enable keepalived"
            cmds.append(cmd)

            for cmd in cmds:
                exec_cmd(cmd, block=True, cwd="/etc/keepalived/")

            print '\033[1;32m finish \033[0m'
    except Exception as err:
        print 'error =\033[1;31m %s \033[0m' % err


def deploy_ms(args):
    '''
    部署主备模式(Master & Slave）
    :param args:
    :return:
    '''
    state = args.s
    master_ip = args.i
    host_name = args.hn
    node_count = args.c
    p = args.p

    print 'state :\033[1;32m %s \033[0m' % state

    if master_ip and master_ip != '127.0.0.1':
        print 'master_ip :\033[1;32m %s \033[0m' % master_ip
        create_redis_sentinel_conf(state, master_ip, node_count)
    if host_name:
        print 'host name :\033[1;32m %s \033[0m' % host_name
        create_mq_conf(state, host_name,p)


def create_redis_sentinel_conf(role, master_ip, node_count):
    try:
        cmds = []
        cmd = "chmod 777 /var/log/redis/sentinel.log"
        cmds.append(cmd)
        redis_bind = commands.getstatusoutput("sed -n '/^bind 0.0.0.0$/'p /etc/redis.conf")[1]
        if not redis_bind:
            cmd = r"sed -i '1 i\bind 0.0.0.0' /etc/redis.conf"
            cmds.append(cmd)

        redis_port = commands.getstatusoutput("sed -n '/^port 6379$/'p /etc/redis.conf")[1]
        if not redis_port:
            cmd = r"sed -i '$a\port 6379' /etc/redis.conf"
            cmds.append(cmd)

        redis_daemonize = commands.getstatusoutput("sed -n '/^daemonize no$/'p /etc/redis.conf")[1]
        if not redis_daemonize:
            cmd = r"sed -i '$a\daemonize no' /etc/redis.conf"
            cmds.append(cmd)

        redis_pro = commands.getstatusoutput("sed -n '/^protected-mode no$/'p /etc/redis.conf")[1]
        if not redis_pro:
            cmd = r"sed -i '$a\protected-mode no' /etc/redis.conf"
            cmds.append(cmd)

        redis_repass = commands.getstatusoutput("sed -n '/^requirepass/'p /etc/redis.conf")[1]
        cmd = r"sed -i '/^requirepass/c requirepass cloud' /etc/redis.conf" if redis_repass else r"sed -i '$a\requirepass cloud' /etc/redis.conf"
        cmds.append(cmd)

        redis_masterauth = commands.getstatusoutput("sed -n '/^masterauth/'p /etc/redis.conf")[1]
        cmd = r"sed -i '/^masterauth/c masterauth cloud' /etc/redis.conf" if redis_masterauth else r"sed -i '$a\masterauth cloud' /etc/redis.conf"
        cmds.append(cmd)

        if role == "0":
            slave_cmd = "sed -n '/^slaveof {master_ip} 6379$/'p /etc/redis.conf".format(master_ip=master_ip)
            redis_slave = commands.getstatusoutput(slave_cmd)[1]
            if not redis_slave:
                cmd = "sed -i '$a\slaveof {master_ip} 6379' /etc/redis.conf".format(master_ip=master_ip)
                cmds.append(cmd)
        cmd = "systemctl restart redis"
        cmds.append(cmd)

        node_count = int(node_count)
        flushall = "/usr/bin/redis-cli -p 6379 -a cloud flushall" if node_count < 3 else ""

        _conf = "#!/bin/bash\n" \
                "status=$(/usr/bin/redis-cli -a cloud info replication | grep role: | " \
                "awk -F \":\" '{print $2}' | awk -F \"\\r\" '{print $1}')\n" \
                "while [ $status ]\n" \
                "do\n" \
                "    if [ $status = 'slave' ]; then\n" \
                "        /usr/bin/redis-cli -p 6379 -a cloud slaveof NO ONE\n" \
                "        if [ $? -eq 0 ]; then\n" \
                "            %s\n" \
                "            break\n" \
                "        fi\n" \
                "    else\n" \
                "        %s\n" \
                "        break\n" \
                "    fi\n" \
                "done" % (flushall,flushall)
        with open("/etc/keepalived/redis_role_switch.sh", "w") as f:
            f.write(_conf)

        # ===========================================redis-sentinel.conf============================================== #

        sentinel_bind = commands.getstatusoutput("sed -n '/^bind 0.0.0.0$/'p /etc/redis-sentinel.conf")[1]
        if not sentinel_bind:
            cmd = r"sed -i '1 i\bind 0.0.0.0' /etc/redis-sentinel.conf"
            cmds.append(cmd)
        sentinel_pro = commands.getstatusoutput(
            "sed -n '/^protected-mode no$/'p /etc/redis-sentinel.conf")[1]
        sentinel_pro1 = commands.getstatusoutput(
            "sed -n '/^# protected-mode no$/'p /etc/redis-sentinel.conf")[1]
        if not sentinel_pro and sentinel_pro1:
            cmd = "sed -i '/^# protected-mode no$/c protected-mode no' /etc/redis-sentinel.conf"
            cmds.append(cmd)
        elif not sentinel_pro:
            cmd = "sed -i '$a\protected-mode no' /etc/redis-sentinel.conf"
            cmds.append(cmd)
        sentinel_port = commands.getstatusoutput("sed -n '/^port 26379$/'p /etc/redis-sentinel.conf")[1]
        if not sentinel_port:
            cmd = "sed -i '$a\port 26379' /etc/redis-sentinel.conf"
            cmds.append(cmd)

        sentinel_monitor = \
            commands.getstatusoutput("sed -n '/^sentinel monitor/'p /etc/redis-sentinel.conf")[1]
        monitor = "sentinel monitor mymaster {master_ip} 6379 2".format(master_ip=master_ip)
        insert_monitor = "sed -i '$a\{monitor}' /etc/redis-sentinel.conf".format(monitor=monitor)
        replace_monitor = "sed -i '/^sentinel monitor/c {monitor}' /etc/redis-sentinel.conf".format(monitor=monitor)
        cmd = replace_monitor if sentinel_monitor else insert_monitor
        cmds.append(cmd)

        sentinel_down = commands.getstatusoutput(
            "sed -n '/^sentinel down-after-milliseconds/'p /etc/redis-sentinel.conf")[1]
        insert_down = "sed -i '$a\sentinel down-after-milliseconds mymaster 5000' /etc/redis-sentinel.conf"
        replace_down = "sed -i '/^sentinel down-after-milliseconds/c sentinel down-after-milliseconds mymaster 5000' /etc/redis-sentinel.conf"

        cmd = replace_down if sentinel_down else insert_down
        cmds.append(cmd)

        sentinel_failover = \
            commands.getstatusoutput("sed -n '/^sentinel failover-timeout/'p /etc/redis-sentinel.conf")[1]

        insert_failover = "sed -i '$a\sentinel failover-timeout mymaster 6000' /etc/redis-sentinel.conf"
        replace_failover = "sed -i '/^sentinel failover-timeout/c sentinel failover-timeout mymaster 6000' /etc/redis-sentinel.conf"

        cmd = replace_failover if sentinel_failover else insert_failover
        cmds.append(cmd)

        sentinel_parallel = \
            commands.getstatusoutput("sed -n '/^sentinel parallel-syncs/'p /etc/redis-sentinel.conf")[1]
        insert_parallel = "sed -i '$a\sentinel parallel-syncs mymaster 2' /etc/redis-sentinel.conf"
        replace_parallel = "sed -i '/^sentinel parallel-syncs/c sentinel parallel-syncs mymaster 2' /etc/redis-sentinel.conf"

        cmd = replace_parallel if sentinel_parallel else insert_parallel
        cmds.append(cmd)

        sentinel_auth = \
            commands.getstatusoutput("sed -n '/^sentinel auth-pass/'p /etc/redis-sentinel.conf")[1]
        insert_auth = "sed -i '$a\sentinel auth-pass mymaster cloud' /etc/redis-sentinel.conf"
        replace_auth = "sed -i '/^sentinel auth-pass/c sentinel auth-pass mymaster cloud' /etc/redis-sentinel.conf"

        cmd = replace_auth if sentinel_auth else insert_auth
        cmds.append(cmd)

        sentinel_log = \
            commands.getstatusoutput("sed -n '/^logfile/'p /etc/redis-sentinel.conf")[1]
        if not sentinel_log:
            cmd = "sed -i '$a\logfile {path}' /etc/redis-sentinel.conf".format(path='"/var/log/redis/sentinel.log"')
            cmds.append(cmd)

        cmd = "sleep 5;systemctl restart redis-sentinel"
        cmds.append(cmd)

        for cmd in cmds:
            exec_cmd(cmd, block=True)
    except Exception as err:
        print 'error =\033[1;31m %s \033[0m' % err


def create_mq_conf(state, host_name, p):
    # 1. 修改hosts,关闭防火墙
    #   host1 和 host2 的
    #   deploy hosts -ih host1_ip,host1_name
    #   deploy hosts -ih host2_ip,host2_name
    #   systemctl stop firewalld
    # 2. 拷贝cookie
    #   将host1的cookie复制到host2
    #   scp /var/lib/rabbitmq/.erlang.cookie host_name:/var/lib/rabbitmq/.erlang,cookie
    # 3. 集群配置
    #   host1 执行，停止rabbitmq服务
    #   systemctl stop rabbitmq-server
    #   rabbitmq-server -detached
    #   host2 执行
    #   systemctl stop rabbitmq-server
    #   rabbitmq-server -detached
    #   rabbitmqctl stop_app
    #   rabbitmqctl join_cluster rabbit@host1_ip
    #   rabbitmqctl start_app
    # 4. 执行
    #   rabbitmqctl set_policy -p / ha-allqueue "^" '{"ha-mode":"all"}'
    try:
        if state == "1":
            cmds = []
            cmd = "systemctl stop firewalld"
            cmds.append(cmd)
            cmd = "sshpass -p {} scp -o StrictHostKeyChecking=no /var/lib/rabbitmq/.erlang.cookie {}:/var/lib/rabbitmq/.erlang.cookie".format(p,host_name)
            cmds.append(cmd)
            cmd = "systemctl stop rabbitmq-server"
            cmds.append(cmd)
            cmd = "rabbitmq-server -detached"
            cmds.append(cmd)

            for cmd in cmds:
                exec_cmd(cmd, block=True)

            cmd = "systemctl restart rabbitmq-server"
            while True:
                time.sleep(5)
                out, err, ret_code = exec_cmd(cmd, block=True)
                if int(ret_code) == 0:
                    break

        if state == "0":
            cmds = []
            cmd = "systemctl stop firewalld"
            cmds.append(cmd)
            cmd = "systemctl stop rabbitmq-server"
            cmds.append(cmd)
            cmd = "rabbitmq-server -detached"
            cmds.append(cmd)
            cmd = "rabbitmqctl stop_app"
            cmds.append(cmd)
            cmd = "rabbitmqctl join_cluster rabbit@{}".format(host_name)
            cmds.append(cmd)
            cmd = "rabbitmqctl start_app"
            cmds.append(cmd)
            cmd = 'rabbitmqctl set_policy -p / ha-allqueue "^" \'{"ha-mode":"all"}\''
            cmds.append(cmd)

            for cmd in cmds:
                exec_cmd(cmd, block=True)

            cmd = "systemctl restart rabbitmq-server"
            while True:
                time.sleep(5)
                out, err, ret_code = exec_cmd(cmd, block=True)
                if int(ret_code) == 0:
                    break

    except Exception as err:
        print 'error =\033[1;31m %s \033[0m' % err


def deploy_hosts(args):
    """
    修改hosts，主机名对应节点ip
    :param args:
    :return:
    """
    try:
        # 获取命令行参数
        args = args.ih.split(',')
        print 'host_ip :\033[1;32m %s \033[0m' % args[0]
        print 'hostname :\033[1;32m %s \033[0m' % args[1]

        # 生成cmd信息
        cmds = []

        cmd = "sed -i '/^{ip}/d' hosts && sed -i '$a\{ip} {hostname}' hosts".format(ip=args[0], hostname=args[1])

        cmds.append(cmd)
        for cmd in cmds:
            exec_cmd(cmd, block=True, cwd="/etc/")

        print '\033[1;32m finish \033[0m'

    except Exception as err:
        print 'error =\033[1;31m %s \033[0m' % err


def deploy_async_msg(args):
    """
    部署rabbitmq消息队列微服务
    :param args:
    :return:
    """
    try:
        # 获取命令行参数
        all_ip = args.eh.split(',')
        database_ip = args.mh
        rabbitmq_ip = args.mq
        net_ip = args.ah
        redis_ip = args.rh
        # print 'database_ip =\033[1;31m %s \033[0m' % database_ip
        print 'database_ip :\033[1;32m %s \033[0m' % database_ip
        print 'eureka_ip :\033[1;32m %s \033[0m' % ','.join(all_ip)
        print 'rabbitmq_ip :\033[1;32m %s \033[0m' % rabbitmq_ip
        print 'redis_ip :\033[1;32m %s \033[0m' % redis_ip
        # 生成数据库信息
        cmds = []
        cmd = create_db_ip_cmd(database_ip)
        cmds += cmd
        cmd = create_eureka_ip_cmd(all_ip)
        cmds.append(cmd)
        cmd = create_mq_ip_cmd(rabbitmq_ip)
        cmds.append(cmd)
        cmd = create_ip_address(net_ip)
        cmds.append(cmd)
        cmd = create_redis_ip_cmd(redis_ip)
        cmds.append(cmd)
        for cmd in cmds:
            exec_cmd(cmd, block=True, cwd="/opt/vcloud/web/cloud-mq/resources/")

        # 激活服务
        cmds = []
        cmd = "systemctl enable async_msg.service"
        cmds.append(cmd)
        cmd = "systemctl restart async_msg.service"
        cmds.append(cmd)
        for cmd in cmds:
            exec_cmd(cmd, block=True)

        print '\033[1;32m finish \033[0m'

    except Exception as err:
        print 'error =\033[1;31m %s \033[0m' % err


def deploy_eureka(args):
    """
    部署注册中心eureka微服务
    :param args:
    :return:
    """
    try:
        # 获取命令行参数
        all_ip = args.eh.split(',')
        net_ip = args.ah
        # print 'database_ip =\033[1;31m %s \033[0m' % database_ip
        print 'eureka_ip :\033[1;32m %s \033[0m' % ','.join(all_ip)

        # 生成数据库信息
        cmds = []

        cmd = create_eureka_ip_cmd(all_ip)
        cmds.append(cmd)
        cmd = create_ip_address(net_ip)
        cmds.append(cmd)
        for cmd in cmds:
            exec_cmd(cmd, block=True, cwd="/opt/vcloud/web/cloud-eureka/resources/")

        # 激活服务
        cmds = []
        cmd = "systemctl enable eureka.service"
        cmds.append(cmd)
        cmd = "systemctl restart eureka.service"
        cmds.append(cmd)
        for cmd in cmds:
            exec_cmd(cmd, block=True)

        print '\033[1;32m finish \033[0m'

    except Exception as err:
        print 'error =\033[1;31m %s \033[0m' % err


def deploy_public(args):
    """
    部署公共的管理微服务
    :param args:
    :return:
    """
    try:
        # 获取命令行参数
        database_ip = args.mh
        all_ip = args.eh.split(',')
        redis_ip = args.rh
        rabbitmq_ip = args.mq
        net_ip = args.ah
        # print 'database_ip =\033[1;31m %s \033[0m' % database_ip
        print 'database_ip :\033[1;32m %s \033[0m' % database_ip
        print 'eureka_ip :\033[1;32m %s \033[0m' % ','.join(all_ip)
        print 'redis_ip :\033[1;32m %s \033[0m' % redis_ip
        print 'rabbitmq_ip :\033[1;32m %s \033[0m' % rabbitmq_ip

        # 生成IP信息
        cmds = []
        cmd = create_db_ip_cmd(database_ip)
        cmds += cmd
        cmd = create_eureka_ip_cmd(all_ip)
        cmds.append(cmd)
        cmd = create_redis_ip_cmd(redis_ip)
        cmds.append(cmd)
        cmd = create_mq_ip_cmd(rabbitmq_ip)
        cmds.append(cmd)
        cmd = create_ip_address(net_ip)
        cmds.append(cmd)
        for cmd in cmds:
            exec_cmd(cmd, block=True, cwd="/opt/vcloud/web/cloud-public/resources/")

        # 激活服务
        cmds = []
        cmd = "systemctl enable public.service"
        cmds.append(cmd)
        cmd = "systemctl restart public.service"
        cmds.append(cmd)
        for cmd in cmds:
            exec_cmd(cmd, block=True)

        print '\033[1;32m finish \033[0m'

    except Exception as err:
        print 'error =\033[1;31m %s \033[0m' % err


def deploy_task(args):
    """
    部署任务管理微服务
    :param args:
    :return:
    """
    try:
        # 获取命令行参数
        database_ip = args.mh
        all_ip = args.eh.split(',')
        redis_ip = args.rh
        rabbitmq_ip = args.mq
        net_ip = args.ah
        # print 'database_ip =\033[1;31m %s \033[0m' % database_ip
        print 'database_ip :\033[1;32m %s \033[0m' % database_ip
        print 'redis_ip :\033[1;32m %s \033[0m' % redis_ip
        print 'eureka_ip :\033[1;32m %s \033[0m' % ','.join(all_ip)
        print 'rabbitmq_ip :\033[1;32m %s \033[0m' % rabbitmq_ip

        # 生成IP信息
        cmds = []

        cmd = create_db_ip_cmd(database_ip)
        cmds += cmd

        cmd = create_eureka_ip_cmd(all_ip)
        cmds.append(cmd)

        cmd = create_redis_ip_cmd(redis_ip)
        cmds.append(cmd)

        cmd = create_mq_ip_cmd(rabbitmq_ip)
        cmds.append(cmd)

        cmd = create_ip_address(net_ip)
        cmds.append(cmd)

        for cmd in cmds:
            exec_cmd(cmd, block=True, cwd="/opt/vcloud/web/cloud-task/resources/")

        # 激活服务
        cmds = []
        cmd = "systemctl enable task.service"
        cmds.append(cmd)
        cmd = "systemctl restart task.service"
        cmds.append(cmd)
        for cmd in cmds:
            exec_cmd(cmd, block=True)

        print '\033[1;32m finish \033[0m'

    except Exception as err:
        print 'error =\033[1;31m %s \033[0m' % err


def deploy_game(args):
    """
    部署云游戏微服务
    :param args:
    :return:
    """
    try:
        # 获取命令行参数
        database_ip = args.mh
        all_ip = args.eh.split(',')
        redis_ip = args.rh
        net_ip = args.ah
        rabbitmq_ip = args.mq
        all_tracker_ip = args.th.split(',')
        print 'database_ip :\033[1;32m %s \033[0m' % database_ip
        print 'redis_ip :\033[1;32m %s \033[0m' % redis_ip
        print 'eureka_ip :\033[1;32m %s \033[0m' % ','.join(all_ip)
        print 'rabbitmq_ip :\033[1;32m %s \033[0m' % rabbitmq_ip
        print 'all_tracker_ip :\033[1;32m %s \033[0m' % ','.join(all_tracker_ip)

        # 生成IP信息
        cmds = []

        cmd = create_db_ip_cmd(database_ip)
        cmds += cmd

        cmd = create_eureka_ip_cmd(all_ip)
        cmds.append(cmd)

        cmd = create_redis_ip_cmd(redis_ip)
        cmds.append(cmd)

        cmd = create_mq_ip_cmd(rabbitmq_ip)
        cmds.append(cmd)

        cmd = create_ip_address(net_ip)
        cmds.append(cmd)

        cmd = create_fastdfs_list(all_tracker_ip)
        cmds.append(cmd)

        cmd = create_fastdfs_web_server(all_tracker_ip)
        cmds.append(cmd)

        for cmd in cmds:
            exec_cmd(cmd, block=True, cwd="/opt/vcloud/web/cloud-game/resources/")

        # 激活服务
        cmds = []
        cmd = "systemctl enable game.service"
        cmds.append(cmd)
        cmd = "systemctl restart game.service"
        cmds.append(cmd)
        for cmd in cmds:
            exec_cmd(cmd, block=True)

        print '\033[1;32m finish \033[0m'

    except Exception as err:
        print 'error =\033[1;31m %s \033[0m' % err


def deploy_storage(args):
    """
    部署超分微服务
    :param args:
    :return:
    """
    try:
        # 获取命令行参数
        database_ip = args.mh
        all_ip = args.eh.split(',')
        redis_ip = args.rh
        net_ip = args.ah
        rabbitmq_ip = args.mq
        gateway_ip = args.gi
        gateway_port = args.gp
        vcfs_path = args.p

        print 'database_ip :\033[1;32m %s \033[0m' % database_ip
        print 'redis_ip :\033[1;32m %s \033[0m' % redis_ip
        print 'eureka_ip :\033[1;32m %s \033[0m' % ','.join(all_ip)
        print 'rabbitmq_ip :\033[1;32m %s \033[0m' % rabbitmq_ip
        print 'gateway_ip :\033[1;32m %s \033[0m' % gateway_ip
        print 'gateway_port :\033[1;32m %s \033[0m' % gateway_port
        print 'vcfs_path :\033[1;32m %s \033[0m' % vcfs_path

        # 生成IP信息
        cmds = []

        cmd = create_db_ip_cmd(database_ip)
        cmds += cmd

        cmd = create_eureka_ip_cmd(all_ip)
        cmds.append(cmd)

        cmd = create_redis_ip_cmd(redis_ip)
        cmds.append(cmd)

        cmd = create_mq_ip_cmd(rabbitmq_ip)
        cmds.append(cmd)

        cmd = create_ip_address(net_ip)
        cmds.append(cmd)

        cmd = create_gateway_ip_cmd(gateway_ip, gateway_port)
        cmds += cmd

        cmd = create_vcfs_path_cmd(vcfs_path)
        cmds.append(cmd)

        for cmd in cmds:
            exec_cmd(cmd, block=True, cwd="/opt/vcloud/web/cloud-storage/resources/")

        # 激活服务
        cmds = []
        cmd = "systemctl enable storage.service"
        cmds.append(cmd)
        cmd = "systemctl restart storage.service"
        cmds.append(cmd)
        for cmd in cmds:
            exec_cmd(cmd, block=True)

        print '\033[1;32m finish \033[0m'

    except Exception as err:
        print 'error =\033[1;31m %s \033[0m' % err


def deploy_game_wsi(args):
    """
    部署云游戏websocket微服务
    :param args:
    :return:
    """
    try:
        # 获取命令行参数
        all_ip = args.eh.split(',')
        net_ip = args.ah
        redis_ip = args.rh
        rabbitmq_ip = args.mq
        print 'eureka_ip :\033[1;32m %s \033[0m' % ','.join(all_ip)

        # 生成IP信息
        cmds = []

        cmd = create_eureka_ip_cmd(all_ip)
        cmds.append(cmd)

        cmd = create_ip_address(net_ip)
        cmds.append(cmd)

        cmd = create_redis_ip_cmd(redis_ip)
        cmds.append(cmd)

        cmd = create_mq_ip_cmd(rabbitmq_ip)
        cmds.append(cmd)

        for cmd in cmds:
            exec_cmd(cmd, block=True, cwd="/opt/vcloud/web/cloud-game-wsi/resources/")

        # 激活服务
        cmds = []
        cmd = "systemctl enable game_wsi.service"
        cmds.append(cmd)
        cmd = "systemctl restart game_wsi.service"
        cmds.append(cmd)
        for cmd in cmds:
            exec_cmd(cmd, block=True)

        print '\033[1;32m finish \033[0m'

    except Exception as err:
        print 'error =\033[1;31m %s \033[0m' % err


def deploy_push(args):
    """
    部署推送服务
    :param args:
    :return:
    """
    try:
        # 获取命令行参数
        all_ip = args.eh.split(',')
        net_ip = args.ah
        redis_ip = args.rh
        print 'eureka_ip :\033[1;32m %s \033[0m' % ','.join(all_ip)
        print 'redis_ip :\033[1;32m %s \033[0m' % redis_ip
        # 生成IP信息
        cmds = []

        cmd = create_eureka_ip_cmd(all_ip)
        cmds.append(cmd)

        cmd = create_ip_address(net_ip)
        cmds.append(cmd)

        cmd = create_redis_ip_cmd(redis_ip)
        cmds.append(cmd)

        for cmd in cmds:
            exec_cmd(cmd, block=True, cwd="/opt/vcloud/web/cloud-push/resources/")

        # 激活服务
        cmds = []
        cmd = "systemctl enable push.service"
        cmds.append(cmd)
        cmd = "systemctl restart push.service"
        cmds.append(cmd)
        for cmd in cmds:
            exec_cmd(cmd, block=True)

        print '\033[1;32m finish \033[0m'

    except Exception as err:
        print 'error =\033[1;31m %s \033[0m' % err


def deploy_user(args):
    """
    部署用户管理微服务
    :param args:
    :return:
    """
    try:
        # 获取命令行参数
        database_ip = args.mh
        all_ip = args.eh.split(',')
        redis_ip = args.rh
        rabbitmq_ip = args.mq
        net_ip = args.ah
        # print 'database_ip =\033[1;31m %s \033[0m' % database_ip
        print 'database_ip :\033[1;32m %s \033[0m' % database_ip
        print 'eureka_ip :\033[1;32m %s \033[0m' % ','.join(all_ip)
        print 'redis_ip :\033[1;32m %s \033[0m' % redis_ip
        print 'rabbitmq_ip :\033[1;32m %s \033[0m' % rabbitmq_ip

        # 生成IP信息
        cmds = []
        cmd = create_db_ip_cmd(database_ip)
        cmds += cmd
        cmd = create_eureka_ip_cmd(all_ip)
        cmds.append(cmd)
        cmd = create_redis_ip_cmd(redis_ip)
        cmds.append(cmd)
        cmd = create_mq_ip_cmd(rabbitmq_ip)
        cmds.append(cmd)
        cmd = create_ip_address(net_ip)
        cmds.append(cmd)
        for cmd in cmds:
            exec_cmd(cmd, block=True, cwd="/opt/vcloud/web/cloud-user/resources/")

        # 获取随机数
        uid = uuid.uuid4()
        verification_code = "vcloud*{uid}".format(uid=uid)

        # 获取当前系统时间
        cur_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))

        db = MySQLdb.Connect(
            "{database_ip}".format(database_ip=database_ip), "cloud", "Cloud.123456", "cloud", charset='utf8'
        )
        cursor = db.cursor()

        insert_sql = "insert into t_license_info(id, license_status, ctime, mtime, uuid," \
                     "license_time, android_num, verification_code)" \
                     "values ('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s')" % \
                     ('1', '0', '{ctime}'.format(ctime=cur_time), '{mtime}'.
                      format(mtime=cur_time), '{uid}'.format(uid=uid), '{license_time}'.format(license_time=cur_time)
                      , '60', '{verification_code}'.format(verification_code=verification_code))

        sql_num = "select * from t_license_info"

        delete_sql = "delete from t_license_info where 1=1;"

        try:
            # 执行SQL语句
            cursor.execute(sql_num)
            result = len(cursor.fetchall())
            # t_license_info只允许有一条数据
            if result > 0:
                cursor.execute(delete_sql)
                cursor.execute(insert_sql)
            else:
                cursor.execute(insert_sql)
            # 提交到数据库执行
            db.commit()
            print "Data insert license_info success"

        except Exception as err:
            # 发生错误时候回滚
            db.rollback()
            print 'error =\033[1;31m %s \033[0m' % err

        cursor.close()
        db.close()

        # 激活服务
        cmds = []
        cmd = "systemctl enable user.service"
        cmds.append(cmd)
        cmd = "systemctl restart user.service"
        cmds.append(cmd)
        for cmd in cmds:
            exec_cmd(cmd, block=True)

        print '\033[1;32m finish \033[0m'

    except Exception as err:
        print 'error =\033[1;31m %s \033[0m' % err


def deploy_upgrade(args):
    """
    部署升级微服务
    :param args:
    :return:
    """
    try:
        # 获取命令行参数
        database_ip = args.mh
        all_ip = args.eh.split(',')
        redis_ip = args.rh
        rabbitmq_ip = args.mq
        net_ip = args.ah
        all_tracker_ip = args.th.split(',')
        # print 'database_ip =\033[1;31m %s \033[0m' % database_ip
        print 'database_ip :\033[1;32m %s \033[0m' % database_ip
        print 'eureka_ip :\033[1;32m %s \033[0m' % ','.join(all_ip)
        print 'redis_ip :\033[1;32m %s \033[0m' % redis_ip
        print 'rabbitmq_ip :\033[1;32m %s \033[0m' % rabbitmq_ip
        print 'all_tracker_ip :\033[1;32m %s \033[0m' % ','.join(all_tracker_ip)
        # 生成IP信息
        cmds = []
        cmd = create_db_ip_cmd(database_ip)
        cmds += cmd
        cmd = create_eureka_ip_cmd(all_ip)
        cmds.append(cmd)
        cmd = create_redis_ip_cmd(redis_ip)
        cmds.append(cmd)
        cmd = create_mq_ip_cmd(rabbitmq_ip)
        cmds.append(cmd)
        cmd = create_ip_address(net_ip)
        cmds.append(cmd)
        cmd = create_fastdfs_list(all_tracker_ip)
        cmds.append(cmd)
        cmd = create_fastdfs_web_server(all_tracker_ip)
        cmds.append(cmd)
        for cmd in cmds:
            exec_cmd(cmd, block=True, cwd="/opt/vcloud/web/cloud-upgrade/resources/")

        # 激活服务
        cmds = []
        cmd = "systemctl enable upgrade.service"
        cmds.append(cmd)
        cmd = "systemctl restart upgrade.service"
        cmds.append(cmd)
        for cmd in cmds:
            exec_cmd(cmd, block=True)

        print '\033[1;32m finish \033[0m'

    except Exception as err:
        print 'error =\033[1;31m %s \033[0m' % err


def deploy_bbs(args):
    """
    部署论坛服务
    :param args:
    :return:
    """
    try:
        # 获取命令行参数
        database_ip = args.mh
        bbs_ip = args.s
        bbs_port = args.p
        # print 'database_ip =\033[1;31m %s \033[0m' % database_ip
        print 'database_ip :\033[1;32m %s \033[0m' % database_ip
        print 'bbs_ip :\033[1;32m %s \033[0m' % bbs_ip
        print 'bbs_port :\033[1;32m %s \033[0m' % bbs_port

        # 生成IP信息
        cmds = []
        cmd = create_db_ip_cmd(database_ip)
        cmds += cmd

        for cmd in cmds:
            exec_cmd(cmd, block=True, cwd="/opt/vcloud/web/cloud-bbs/")

        # cmd = """mysql -u root -Cloud.123456 -e "CHANGE MASTER TO MASTER_HOST='{master_host}',MASTER_PORT=3306,
        #         MASTER_USER='cloud',MASTER_PASSWORD='Cloud.123456',MASTER_LOG_FILE='{master_log_file}',
        #         MASTER_LOG_POS={master_log_pos}" """. \
        #     format(master_host=master_host, master_log_file=master_log_file, master_log_pos=master_log_pos)

        db = MySQLdb.Connect(
            "{database_ip}".format(database_ip=database_ip), "cloud", "Cloud.123456", "cloud", charset='utf8'
        )

        if bbs_port == 80:
            addr = bbs_ip
        else:
            addr = "%s:%s" % (bbs_ip, bbs_port)
        cursor = db.cursor()
        update_sql = """update system_config set value="http://%s" where id="2" """ % addr
        cursor.execute(update_sql)
        update_sql = """update system_config set value="http://%s/static/upload/" where id="18" """ % addr
        cursor.execute(update_sql)
        db.commit()

        cursor.close()
        db.close()

        # 激活服务
        cmds = []
        cmd = "systemctl enable bbs.service"
        cmds.append(cmd)
        cmd = "systemctl restart bbs.service"
        cmds.append(cmd)
        for cmd in cmds:
            exec_cmd(cmd, block=True)

        print '\033[1;32m finish \033[0m'

    except Exception as err:
        print 'error =\033[1;31m %s \033[0m' % err


def deploy_wsi(args):
    """
    部署webSocket微服务
    :param args:
    :return:
    """
    try:
        # 获取命令行参数
        database_ip = args.mh
        all_ip = args.eh.split(',')
        redis_ip = args.rh
        net_ip = args.ah
        all_tracker_ip = args.th.split(',')
        print 'database_ip :\033[1;32m %s \033[0m' % database_ip
        print 'redis_ip :\033[1;32m %s \033[0m' % redis_ip
        print 'eureka_ip :\033[1;32m %s \033[0m' % ','.join(all_ip)
        print 'all_tracker_ip :\033[1;32m %s \033[0m' % ','.join(all_tracker_ip)

        # 生成IP信息
        cmds = []

        cmd = create_db_ip_cmd(database_ip)
        cmds += cmd

        cmd = create_eureka_ip_cmd(all_ip)
        cmds.append(cmd)

        cmd = create_redis_ip_cmd(redis_ip)
        cmds.append(cmd)

        cmd = create_ip_address(net_ip)
        cmds.append(cmd)

        cmd = create_fastdfs_list(all_tracker_ip)
        cmds.append(cmd)
        cmd = create_fastdfs_web_server(all_tracker_ip)
        cmds.append(cmd)

        for cmd in cmds:
            exec_cmd(cmd, block=True, cwd="/opt/vcloud/web/cloud-wsi/resources/")

        # 激活服务
        cmds = []
        cmd = "systemctl enable wsi.service"
        cmds.append(cmd)
        cmd = "systemctl restart wsi.service"
        cmds.append(cmd)
        for cmd in cmds:
            exec_cmd(cmd, block=True)

        print '\033[1;32m finish \033[0m'

    except Exception as err:
        print 'error =\033[1;31m %s \033[0m' % err


def deploy_zuul(args):
    """
    部署网关微服务
    :param args:
    :return:
    """
    try:
        # 获取命令行参数
        all_ip = args.eh.split(',')
        net_ip = args.ah
        # print 'database_ip =\033[1;31m %s \033[0m' % database_ip
        print 'eureka_ip :\033[1;32m %s \033[0m' % ','.join(all_ip)

        # 生成数据库信息
        cmds = []

        cmd = create_eureka_ip_cmd(all_ip)
        cmds.append(cmd)

        cmd = create_ip_address(net_ip)
        cmds.append(cmd)

        for cmd in cmds:
            exec_cmd(cmd, block=True, cwd="/opt/vcloud/web/cloud-zuul/resources/")

        # 激活服务
        cmds = []
        cmd = "systemctl enable zuul.service"
        cmds.append(cmd)
        cmd = "systemctl restart zuul.service"
        cmds.append(cmd)
        for cmd in cmds:
            exec_cmd(cmd, block=True)

        print '\033[1;32m finish \033[0m'

    except Exception as err:
        print 'error =\033[1;31m %s \033[0m' % err


def deploy_nginx(args):
    """
    部署nginx，实现负载均衡
    :param args:
    :return:
    """
    try:
        # 获取命令行参数
        zuul_ips = args.i.strip(',').split(',')
        print 'vcmp_ips :\033[1;32m %s \033[0m' % zuul_ips
        ws_ips = args.ws.strip(',').split(',')
        print 'ws_ips :\033[1;32m %s \033[0m' % ws_ips
        file_ips = args.f.strip(',').split(',')
        print 'file_ips :\033[1;32m %s \033[0m' % file_ips
        gws_ips = args.gws.strip(',').split(',')
        print 'gws_ips :\033[1;32m %s \033[0m' % gws_ips
        ins_ips = args.ins.strip(',').split(',')
        print 'ins_ips :\033[1;32m %s \033[0m' % ins_ips
        p_ips = args.p.strip(',').split(',')
        print 'p_ips :\033[1;32m %s \033[0m' % p_ips
        up_ips = args.up.strip(',').split(',')
        print 'up_ips :\033[1;32m %s \033[0m' % up_ips
        nac_ips = args.nac.strip(',').split(',')
        print 'nac_ips :\033[1;32m %s \033[0m' % nac_ips

        cmds = []
        # 修改nginx配置文件
        # cmd = "sed -i -e '/:8011/d' -e '/:8013/d' -e '/:8020/d' -e '/:8022/d' -e '/:8030/d' -e '/:8033/d' /etc/nginx/conf.d/vcloud.conf"
        # cmds.append(cmd)
        # cmd = "sed -i -e '/ ip_hash;/d' /etc/nginx/conf.d/vcloud.conf"
        # cmds.append(cmd)

        if zuul_ips:
            cmd = "sed -i -e '/:8011/d' /etc/nginx/conf.d/vcloud.conf"
            cmds.append(cmd)
        if ws_ips:
            cmd = "sed -i -e '/:8013/d' /etc/nginx/conf.d/vcloud.conf"
            cmds.append(cmd)
        if file_ips:
            cmd = "sed -i -e '/:8020/d' /etc/nginx/conf.d/vcloud.conf"
            cmds.append(cmd)
        if gws_ips:
            cmd = "sed -i -e '/0.0.0.0:8022/d' /etc/nginx/conf.d/vcloud.conf"
            cmds.append(cmd)
        if ins_ips:
            cmd = "sed -i -e '/:8030/d' /etc/nginx/conf.d/vcloud.conf"
            cmds.append(cmd)
        if p_ips:
            cmd = "sed -i -e '/:8025/d' /etc/nginx/conf.d/vcloud.conf"
            cmds.append(cmd)
        if up_ips:
            cmd = "sed -i -e '/:8033/d' /etc/nginx/conf.d/vcloud.conf"
            cmds.append(cmd)
        if nac_ips:
            cmd = "sed -i -e '/:8848/d' /etc/nginx/conf.d/vcloud.conf"
            cmds.append(cmd)

        for zuul_ip in zuul_ips:
            cmd = "sed -i '/upstream vcloud.com/a\    server {zuul_ip}:8011 max_fails=1 " \
                  "fail_timeout=30s;' /etc/nginx/conf.d/vcloud.conf".format(zuul_ip=zuul_ip)
            cmds.append(cmd)

        for ws_ip in ws_ips:
            cmd = "sed -i '/upstream wsi.com/a\    server {ws_ip}:8013 max_fails=1 " \
                  "fail_timeout=30s;' /etc/nginx/conf.d/vcloud.conf".format(ws_ip=ws_ip)
            cmds.append(cmd)

        for file_ip in file_ips:
            cmd = "sed -i '/upstream file.com/a\    server {file_ip}:8020 max_fails=1 " \
                  "fail_timeout=30s;' /etc/nginx/conf.d/vcloud.conf".format(file_ip=file_ip)
            cmds.append(cmd)

        for gws_ip in gws_ips:
            cmd = "sed -i '/upstream gameWsi.com/a\    server {gws_ip}:8022 max_fails=1 " \
                  "fail_timeout=30s;' /etc/nginx/conf.d/vcloud.conf".format(gws_ip=gws_ip)
            cmds.append(cmd)

        for ins_ip in ins_ips:
            cmd = "sed -i '/upstream insight.com/a\    server {ins_ip}:8030 max_fails=1 " \
                  "fail_timeout=30s;' /etc/nginx/conf.d/vcloud.conf".format(ins_ip=ins_ip)
            cmds.append(cmd)

        for p_ip in p_ips:
            cmd = "sed -i '/upstream push.com/a\    server {p_ip}:8025 max_fails=1 " \
                  "fail_timeout=30s;' /etc/nginx/conf.d/vcloud.conf".format(p_ip=p_ip)
            cmds.append(cmd)

        for up_ip in up_ips:
            cmd = "sed -i '/upstream upgrade_py.com/a\    server {up_ip}:8033 max_fails=1 " \
                  "fail_timeout=30s;' /etc/nginx/conf.d/vcloud.conf".format(up_ip=up_ip)
            cmds.append(cmd)

        for nac_ip in nac_ips:
            cmd = "sed -i '/upstream nacos.com/a\    server {nac_ip}:8848 max_fails=1 " \
                  "fail_timeout=30s;' /etc/nginx/conf.d/vcloud.conf".format(nac_ip=nac_ip)
            cmds.append(cmd)


        # cmd = "sed -i '/upstream vcloud.com/a\    ip_hash;' /etc/nginx/conf.d/vcloud.conf"
        # cmds.append(cmd)
        # cmd = "sed -i '/upstream wsi.com/a\    ip_hash;' /etc/nginx/conf.d/vcloud.conf"
        # cmds.append(cmd)

        # 重启nginx服务
        cmd = "systemctl restart nginx"
        cmds.append(cmd)
        cmd = "systemctl enable nginx"
        cmds.append(cmd)

        # 执行命令
        for cmd in cmds:
            exec_cmd(cmd, block=True)

        print '\033[1;32m finish \033[0m'

    except Exception as err:
        print 'error =\033[1;31m %s \033[0m' % err


def deploy_net(args):
    """
    部署内外网关系
    :param args:
    :return:
    """
    try:
        # 获取命令行参数
        database_ip = args.mh
        intranet_ip = args.ih
        public_ip = args.nh

        print 'database_ip :\033[1;32m %s \033[0m' % database_ip
        print 'intranet_ip :\033[1;32m %s \033[0m' % intranet_ip
        print 'public_ip :\033[1;32m %s \033[0m' % public_ip


        net_ip = "insert into t_net_ip(server_name,server_ip,net_ip) values ('%s', '%s' , '%s')" % \
                  ('auth', '{intranet_ip}'.format(intranet_ip = intranet_ip), '{public_ip}'.format(public_ip = public_ip))


        select_net_ip = "select * from t_net_ip where server_name = 'auth'"

        delete_sql = "delete from t_net_ip where server_name = 'auth'"


        db = MySQLdb.Connect(
            "{database_ip}".format(database_ip=database_ip), "cloud", "Cloud.123456", "cloud", charset='utf8'
        )
        cursor = db.cursor()

        try:
            # 执行SQL语句
            cursor.execute(select_net_ip)
            result = len(cursor.fetchall())

            if result > 0:
                cursor.execute(delete_sql)
                cursor.execute(net_ip)
            else:
                cursor.execute(net_ip)
            # 提交到数据库执行
            db.commit()
            print "Data insert net_ip success"

        except Exception as err:
            # 发生错误时候回滚
            db.rollback()
            print 'error =\033[1;31m %s \033[0m' % err

        cursor.close()
        db.close()

        print '\033[1;32m finish \033[0m'

    except Exception as err:
        print 'error =\033[1;31m %s \033[0m' % err


def deploy_visit(args):
    """
    部署nginx虚拟ip地址
    :param args:
    :return:
    """
    try:
        # 获取命令行参数
        database_ip = args.mh
        virtual_ip = args.vh

        print 'database_ip :\033[1;32m %s \033[0m' % database_ip
        print 'virtual_ip :\033[1;32m %s \033[0m' % virtual_ip



        insert_virtual_ip = "insert into t_net_ip(server_name,server_ip) values ('%s', '%s')" % \
                  ('virtualIp', '{virtual_ip}'.format(virtual_ip = virtual_ip))


        slect_virtual_ip = "select * from t_net_ip where server_name = 'virtualIp'"

        delete_virtual_ip = "delete from t_net_ip where server_name = 'virtualIp'"



        db = MySQLdb.Connect(
            "{database_ip}".format(database_ip=database_ip), "cloud", "Cloud.123456", "cloud", charset='utf8'
        )
        cursor = db.cursor()

        try:
            # 执行SQL语句
            cursor.execute(slect_virtual_ip)
            result = len(cursor.fetchall())

            if result > 0:
                cursor.execute(delete_virtual_ip)
                cursor.execute(insert_virtual_ip)
            else:
                cursor.execute(insert_virtual_ip)
            # 提交到数据库执行
            db.commit()
            print "virtualIp Data insert net_ip success"

        except Exception as err:
            # 发生错误时候回滚
            db.rollback()
            print 'error =\033[1;31m %s \033[0m' % err

        cursor.close()
        db.close()

        print '\033[1;32m finish \033[0m'

    except Exception as err:
        print 'error =\033[1;31m %s \033[0m' % err


def deploy_fastdfs(args):
    """
    部署高可用文件系统集群
    :param args:
    :return:
    """
    try:
        # 获取命令行参数
        tarcker_ips = args.th.strip(',').split(',')
        print 'tracker_ips :\033[1;32m %s \033[0m' % tarcker_ips
        allow_hosts_ips = args.ah.strip(',').split(',')
        print 'allow_hosts_ips :\033[1;32m %s \033[0m' % allow_hosts_ips
        bind_addr = args.bh
        print 'bind_addr :\033[1;32m %s \033[0m' % bind_addr

        storage_conf_file = "/etc/fdfs/storage.conf"

        cmds = []
        # 修改stroage.conf配置文件中的tracker_server监视
        cmd = "sed -i -e '/tracker_server/d' -e '/allow_hosts/d' /etc/fdfs/storage.conf"
        cmds.append(cmd)

        if bind_addr != "0.0.0.0":
         #选择性修改bind_addr绑定本地ip的值
            cmd = "sed -i '/^bind_addr/c bind_addr={bind_addr}' /etc/fdfs/storage.conf".format(bind_addr=bind_addr)
            cmds.append(cmd)

        for tarcker_ip in tarcker_ips:
            cmd = "sed -i '$a tracker_server={tarcker_ip}:22122' {storage_conf_file}"\
                .format(tarcker_ip=tarcker_ip,storage_conf_file=storage_conf_file)
            cmds.append(cmd)

        for allow_hosts_ip in allow_hosts_ips:
            cmd = "sed -i '$a allow_hosts={allow_hosts_ip}' {storage_conf_file}"\
                .format(allow_hosts_ip=allow_hosts_ip,storage_conf_file=storage_conf_file)
            cmds.append(cmd)

        cmd = "mkdir -p /opt/fastdfs/fastdfs_tracker"
        cmds.append(cmd)
        cmd = "mkdir -p /opt/fastdfs/storage01/fastdfs_storage"
        cmds.append(cmd)
        cmd = "mkdir -p /opt/fastdfs/storage01/fastdfs_storage_data"
        cmds.append(cmd)

        # 重启服务
        cmd = "service fdfs_trackerd restart"
        cmds.append(cmd)
        cmd = "sleep 5; service fdfs_storaged restart"
        cmds.append(cmd)

        cmd = "chkconfig --add fdfs_trackerd"
        cmds.append(cmd)
        cmd = "chkconfig --add fdfs_storaged"
        cmds.append(cmd)


        # 执行命令
        for cmd in cmds:
            exec_cmd(cmd, block=True)

        print '\033[1;32m finish \033[0m'

    except Exception as err:
        print 'error =\033[1;31m %s \033[0m' % err


def deploy_mysql(args):
    """
    mysql主主同步方案部署，实现数据库容灾
    :param args:
    :return:
    """
    try:
        # 获取命令行参数
        mysql_index = int(args.n)
        master_host = args.i
        mysql_master_log_info = args.m
        master_status = args.s
        init = args.init

        cmds = []

        if master_status != 0:
            show_slave_status()
        elif init != 0:
            initialize_database()
        elif mysql_index != 0:
            print 'mysql_index :\033[1;32m %s \033[0m' % mysql_index

            if mysql_index % 2 == 0:
                offset = 1
            else:
                offset = 2
            # mysql 配置文件修改
            mod_mysql_conf(mysql_index, offset)

        elif master_host != "127.0.0.1" and mysql_master_log_info:
            master_info = mysql_master_log_info.split(":")
            if len(master_info) >= 2:
                master_log_file = master_info[0]
                master_log_pos = master_info[1]
                print 'master_host :\033[1;32m %s \033[0m' % master_host
                print 'MASTER_LOG_FILE :\033[1;32m %s \033[0m' % master_log_file
                print 'MASTER_LOG_POS :\033[1;32m %s \033[0m' % master_log_pos
                # 主主同步
                set_mysql_master(master_host, master_log_file, master_log_pos)

            else:
                print '\033[1;31m mysql_master_log_info ERROR \033[0m'

        else:
            print '\033[1;31m The parameter format is incorrect. \033[0m'

        # 执行命令
        for cmd in cmds:
            exec_cmd(cmd, True)

        print '\033[1;32m finish \033[0m'

    except Exception as err:
        print 'error =\033[1;31m %s \033[0m' % err

def deploy_insight(args):
    """
    超分智能管理部署
    :param args:
    :return:
    """
    try:
        # 获取命令行参数
        database_ip = args.mh
        redis_ip = args.rh
        net_ip = args.ah

        print 'database_ip :\033[1;32m %s \033[0m' % database_ip
        print 'redis_ip :\033[1;32m %s \033[0m' % redis_ip

        # 生成ip信息
        # cmds = []
        # cmd = create_db_ip_cmd(database_ip)
        # cmds += cmd
        # cmd = create_eureka_ip_cmd(all_ip)
        # cmds.append(cmd)
        # cmd = create_ip_address(net_ip)
        # cmds.append(cmd)
        # for cmd in cmds:
        #     exec_cmd(cmd, block=True, cwd="/opt/vcloud/web/cloud-insight/resources/")

        conf_path = "/opt/vcloud/web/cloud-insight"
        cp = ConfigParser.ConfigParser()
        cp.read(os.path.join(conf_path, "config"))

        # 获取指定配置文件
        # res = cp.get("timeout_allocation", "host")
        # 修改指定配置文件，没有则创建
        cp.set("timeout_allocation", "host", net_ip)
        cp.set("app_name", "host", net_ip)
        cp.set("mysql", "db_host", database_ip)
        cp.set("redis", "rd_host", redis_ip)
        cp.write(open(os.path.join(conf_path, "config"), "w"))

        # 激活服务
        cmds = []
        cmd = "systemctl enable insight.service"
        cmds.append(cmd)
        cmd = "systemctl restart insight.service"
        cmds.append(cmd)
        for cmd in cmds:
            exec_cmd(cmd, block=True)

        print '\033[1;32m finish \033[0m'

    except Exception as err:
        print 'error =\033[1;31m %s \033[0m' % err


def deploy_upgrade_py(args):
    """
    平台升级部署
    :param args:
    :return:
    """
    try:
        # 获取命令行参数
        database_ip = args.mh
        redis_ip = args.rh
        net_ip = args.ah.split(',')

        print 'database_ip :\033[1;32m %s \033[0m' % database_ip
        print 'redis_ip :\033[1;32m %s \033[0m' % redis_ip
        print 'node_ip :\033[1;32m %s \033[0m' % net_ip

        # 生成ip信息
        # cmds = []
        # cmd = create_db_ip_cmd(database_ip)
        # cmds += cmd
        # cmd = create_eureka_ip_cmd(all_ip)
        # cmds.append(cmd)
        # cmd = create_ip_address(net_ip)
        # cmds.append(cmd)
        # for cmd in cmds:
        #     exec_cmd(cmd, block=True, cwd="/opt/vcloud/web/cloud-insight/resources/")

        conf_path = "/opt/vcloud/web/cloud-upgrade-py"
        cp = ConfigParser.ConfigParser()
        cp.read(os.path.join(conf_path, "config"))

        # 获取指定配置文件
        # res = cp.get("timeout_allocation", "host")
        # 修改指定配置文件，没有则创建
        host_len = len(net_ip)
        for i in range(host_len):
            cp.set("hostname", "host{}".format(i), net_ip[i])
        cp.set("mysql", "db_host", database_ip)
        cp.set("redis", "rd_host", redis_ip)
        cp.write(open(os.path.join(conf_path, "config"), "w"))

        # 激活服务
        cmds = []
        cmd = "systemctl enable upgrade_py.service"
        cmds.append(cmd)
        cmd = "systemctl restart upgrade_py.service"
        cmds.append(cmd)
        for cmd in cmds:
            exec_cmd(cmd, block=True)

        print '\033[1;32m finish \033[0m'

    except Exception as err:
        print 'error =\033[1;31m %s \033[0m' % err


def deploy_nacos(args):
    try:

        init = args.init
        host = args.i
        cluster = args.ct
        mode = args.m
        cmds = []
        if init != 0:
            initialize_nacos_database()
        if host != "127.0.0.1":
            cmd = "sed -i '/^# nacos.inetutils.ip-address=/c nacos.inetutils.ip-address={}' /opt/vcloud/web/nacos/conf/application.properties && sed -i '/^nacos.inetutils.ip-address=/c nacos.inetutils.ip-address={}' /opt/vcloud/web/nacos/conf/application.properties".format(host,host)
            cmds.append(cmd)
            cmd = "sed -i '/^# spring.datasource.platform=mysql/c spring.datasource.platform=mysql' /opt/vcloud/web/nacos/conf/application.properties"
            cmds.append(cmd)
            cmd = "sed -i '/^# db.num=1/c db.num=1' /opt/vcloud/web/nacos/conf/application.properties"
            cmds.append(cmd)
            cmd = "sed -i '/^# db.url.0=jdbc:mysql/c db.url.0=jdbc:mysql://{}:3306/nacos?characterEncoding=utf8&connectTimeout=1000&socketTimeout=3000&autoReconnect=true&useUnicode=true&useSSL=false&serverTimezone=UTC' /opt/vcloud/web/nacos/conf/application.properties && sed -i '/^db.url.0=jdbc:mysql/c db.url.0=jdbc:mysql://{}:3306/nacos?characterEncoding=utf8&connectTimeout=1000&socketTimeout=3000&autoReconnect=true&useUnicode=true&useSSL=false&serverTimezone=UTC' /opt/vcloud/web/nacos/conf/application.properties".format(host, host)
            cmds.append(cmd)
            cmd = "sed -i '/^# db.user.0=/c db.user.0=cloud' /opt/vcloud/web/nacos/conf/application.properties"
            cmds.append(cmd)
            cmd = "sed -i '/^# db.password.0=/c db.password.0=Cloud.123456' /opt/vcloud/web/nacos/conf/application.properties"
            cmds.append(cmd)
        if cluster != "127.0.0.1":
            cmd = "\cp -rf /opt/vcloud/web/nacos/conf/cluster.conf.example /opt/vcloud/web/nacos/conf/cluster.conf"
            cmds.append(cmd)
            # cmd = "sed -i '/#example/q' /opt/vcloud/web/nacos/conf/cluster.conf"
            cmd = "sed -i '/#example/{n;d}' /opt/vcloud/web/nacos/conf/cluster.conf"
            cmds.append(cmd)
            cmd = "sed -i '/#example/{n;d}' /opt/vcloud/web/nacos/conf/cluster.conf"
            cmds.append(cmd)
            cmd = "sed -i '/#example/{n;d}' /opt/vcloud/web/nacos/conf/cluster.conf"
            cmds.append(cmd)
            ip_list = cluster.split(",")
            for ip in ip_list:
                cmd = "sed -i '$a\\{}' /opt/vcloud/web/nacos/conf/cluster.conf".format(ip)
                cmds.append(cmd)
        if mode != 0:
            if mode == 1:
                cmd = "sh /opt/vcloud/web/nacos/bin/startup.sh -m standalone"
                cmds.append(cmd)
            elif mode == 2:
                cmd = "sh /opt/vcloud/web/nacos/bin/startup.sh"
                cmds.append(cmd)

        for cmd in cmds:
            exec_cmd(cmd, block=True)

        print '\033[1;32m finish \033[0m'

    except Exception as err:
        print 'error =\033[1;31m %s \033[0m' % err


def initialize_nacos_database():
    """
    初始化nacos数据库
    :return:
    """
    try:
        cmds = []
        cmd = "mysql -u cloud -pCloud.123456 < /opt/vcloud/web/nacos/conf/nacos-mysql.sql"
        cmds.append(cmd)
        for cmd in cmds:
            exec_cmd(cmd, block=True)

    except Exception as err:
        print 'error =\033[1;31m %s \033[0m' % err



def mod_mysql_conf(mysql_index, offset):
    """
    修改mysql配置文件
    :param mysql_index:
    :param offset:
    :return:
    """
    try:
        mysql_conf_file = "/etc/my.cnf"

        cmds = []
        cmd = "sed -i '/^server-id/d' /etc/my.cnf && sed -i '$a server-id={mysql_index}' {mysql_conf_file}". \
            format(mysql_index=mysql_index, mysql_conf_file=mysql_conf_file)
        cmds.append(cmd)
        cmd = "sed -i '/^log-bin/d' /etc/my.cnf && sed -i '$a log-bin=mysql_bin' {mysql_conf_file}". \
            format(mysql_conf_file=mysql_conf_file)
        cmds.append(cmd)
        cmd = "sed -i '/^binlog_do_db/d' /etc/my.cnf && sed -i '$a binlog_do_db=cloud' {mysql_conf_file}". \
            format(mysql_conf_file=mysql_conf_file)
        cmds.append(cmd)
        cmd = "sed -i '/^replicate-do-db/d' /etc/my.cnf && sed -i '$a replicate-do-db=cloud' {mysql_conf_file}". \
            format(mysql_conf_file=mysql_conf_file)
        cmds.append(cmd)
        cmd = "sed -i '/^replicate-do-db/d' /etc/my.cnf && sed -i '$a auto-increment-offset={offset}' " \
              "{mysql_conf_file}".format(offset=offset, mysql_conf_file=mysql_conf_file)
        cmds.append(cmd)
        cmd = "sed -i '/^auto-increment-increment/d' /etc/my.cnf && sed -i '$a auto-increment-increment=2' " \
              "{mysql_conf_file}".format(mysql_conf_file=mysql_conf_file)
        cmds.append(cmd)
        cmd = "sed -i '/^log_bin_trust_function_creators/d' /etc/my.cnf && sed -i '$a " \
              "log_bin_trust_function_creators=1' {mysql_conf_file}".format(mysql_conf_file=mysql_conf_file)
        cmds.append(cmd)
        cmd = "sed -i '/^expire_logs_days/d' /etc/my.cnf && sed -i '$a expire_logs_days=10' {mysql_conf_file}". \
            format(mysql_conf_file=mysql_conf_file)
        cmds.append(cmd)
        cmd = "sed -i '/^max_binlog_size/d' /etc/my.cnf && sed -i '$a max_binlog_size=100M' {mysql_conf_file}". \
            format(mysql_conf_file=mysql_conf_file)
        cmds.append(cmd)
        cmd = "sed -i '/^max_connections/d' /etc/my.cnf && sed -i '$a max_connections=2000' {mysql_conf_file}". \
            format(mysql_conf_file=mysql_conf_file)
        cmds.append(cmd)
        cmd = "sed -i '/^skip-name-resolve/d' /etc/my.cnf && sed -i '$a skip-name-resolve' {mysql_conf_file}". \
            format(mysql_conf_file=mysql_conf_file)
        cmds.append(cmd)
        cmd = "sed -i '/^wait_timeout/d' /etc/my.cnf && sed -i '$a wait_timeout=2880000' {mysql_conf_file}". \
            format(mysql_conf_file=mysql_conf_file)
        cmds.append(cmd)
        cmd = "sed -i '/^interactive_timeout/d' /etc/my.cnf && sed -i '$a interactive_timeout=2880000' " \
              "{mysql_conf_file}". \
            format(mysql_conf_file=mysql_conf_file)
        cmds.append(cmd)
        cmd = "sed -i '/^max_allowed_packet/d' /etc/my.cnf && sed -i '$a max_allowed_packet=64M' {mysql_conf_file}". \
            format(mysql_conf_file=mysql_conf_file)
        cmds.append(cmd)
        cmd = "sed -i '/^skip_ssl/d' /etc/my.cnf && sed -i '$a skip_ssl' {mysql_conf_file}". \
            format(mysql_conf_file=mysql_conf_file)
        cmds.append(cmd)
        cmd = "sed -i '/^slave-skip-errors/d' /etc/my.cnf && sed -i '$a slave-skip-errors=1032' {mysql_conf_file}". \
            format(mysql_conf_file=mysql_conf_file)
        cmds.append(cmd)

        cmd = "systemctl restart mysqld"
        cmds.append(cmd)

        cmd = """mysql -u root -pCloud.123456 -e "GRANT REPLICATION SLAVE ON *.* to 'cloud'@'%' " """
        cmds.append(cmd)
        cmd = """mysql -u root -pCloud.123456 -e "FLUSH PRIVILEGES" """
        cmds.append(cmd)
        cmd = """mysql -u root -pCloud.123456 -e "reset master" """
        cmds.append(cmd)

        # 执行命令
        for cmd in cmds:
            exec_cmd(cmd, block=True)

        # 获取主从复制中的master信息
        cmd = """mysql -u root -pCloud.123456 -e "show master
        status\G" | grep -E "File:|Position:" | awk -F ":" '{print $2}'"""
        stdout, err, stat = exec_cmd(cmd, True)
        log_info = stdout.readlines()
        if len(log_info) >= 2:
            master_log_file = log_info[0].strip()
            master_log_pos = log_info[1].strip()
            print '\033[1;32m MASTER_LOG_FILE:MASTER_LOG_POS = %s:%s \033[0m' % (master_log_file, master_log_pos)

    except Exception as err:
        print 'error =\033[1;31m %s \033[0m' % err


def set_mysql_master(master_host, master_log_file, master_log_pos):
    """
    配置主主复制
    :param master_host:
    :param master_log_file:
    :param master_log_pos:
    :return:
    """
    try:
        cmds = []
        cmd = """mysql -u root -pCloud.123456 -e "stop slave" """
        cmds.append(cmd)
        cmd = """mysql -u root -pCloud.123456 -e "CHANGE MASTER TO MASTER_HOST='{master_host}',MASTER_PORT=3306,
        MASTER_USER='cloud',MASTER_PASSWORD='Cloud.123456',MASTER_LOG_FILE='{master_log_file}',
        MASTER_LOG_POS={master_log_pos}" """. \
            format(master_host=master_host, master_log_file=master_log_file, master_log_pos=master_log_pos)
        cmds.append(cmd)
        cmd = """mysql -u root -pCloud.123456 -e "start slave" """
        cmds.append(cmd)

        # 执行命令
        for cmd in cmds:
            exec_cmd(cmd, True)

    except Exception as err:
        print 'error =\033[1;31m %s \033[0m' % err


def show_slave_status():
    """
    查看主主复制状态
    :return:
    """
    try:
        cmd = """mysql -u root -pCloud.123456 -e "show slave
        status\G" | grep -E "Master_Host:|Slave_IO_Running:|Slave_SQL_Running:" """
        stdout, err, stat = exec_cmd(cmd, True)
        slave_status = stdout.readlines()
        for cont in slave_status:
            print '\033[1;32m%s\033[0m' % cont

    except Exception as err:
        print 'error =\033[1;31m %s \033[0m' % err


def initialize_database():
    """
    初始化数据库
    :return:
    """
    try:
        # cmds = []
        # cmd = "mysql -u cloud -pCloud.123456 < /opt/vcloud/web/mysql/V1.0/cloud.sql"
        # cmds.append(cmd)
        # cmd = "python /opt/vcloud/web/mysql/V3.0/add_script_add_credits_order_num.py"
        # cmds.append(cmd)
        # cmd = "python /opt/vcloud/web/mysql/V3.0/add_script_add_give_star_num.py"
        # cmds.append(cmd)
        # cmd = "mysql -u cloud -pCloud.123456 < /opt/vcloud/web/mysql/V3.0/cloud-v3.0.sql"
        # cmds.append(cmd)
        # for cmd in cmds:
        #     exec_cmd(cmd, block=True, cwd="/opt/vcloud/web/mysql")
        path_list = sorted(get_mysql_path())
        get_py_file(path_list)

    except Exception as err:
        print 'error =\033[1;31m %s \033[0m' % err


# 获取mysql文件夹路径
def get_mysql_path():
    try:
        path = "/opt/vcloud/web/mysql/"
        path_list = []
        for root, dirs, files in os.walk(path):
            for dir in dirs:
                dir_path = os.path.join(root, dir)
                path_list.append(dir_path)

        return path_list
    except Exception as err:
        print 'error =\033[1;31m %s \033[0m' % err

# 获取mysql文件路径
def get_py_file(path_list):
    try:
        for path in path_list:
            for root, dirs, files in os.walk(path):
                sql_cmd = ""
                for file in files:
                    path_file = os.path.join(root, file)
                    if ".sql" in path_file:
                        sql_cmd = path_file
                    elif ".py" in path_file:
                        cmd = "python {}".format(path_file)
                        exec_cmd(cmd)
                if sql_cmd:
                    cmd = "mysql -u cloud -pCloud.123456 < {}".format(sql_cmd)
                    exec_cmd(cmd)
    except Exception as err:
        print 'error =\033[1;31m %s \033[0m' % err


def perfect_square(val):
    """
    自定义格式
    :param val:
    :return:
    """
    vals = val.split(',')
    pattern = r"^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$"
    for value in vals:
        if not re.match(pattern, value):
            print '\033[1;31m The parameter format is incorrect. \033[0m'
            msg = "The parameter format is incorrect."
            raise argparse.ArgumentTypeError(msg)
    return val


def check_hosts(val):
    """
    检测hosts
    :param val:
    :return:
    """
    vals = val.split(',')
    pattern = r"^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$"
    if not len(vals) == 2 or not re.match(pattern, vals[0]):
        print '\033[1;31m The parameter format is incorrect. \033[0m'
        msg = "The parameter format is incorrect."
        raise argparse.ArgumentTypeError(msg)
    return val


def kpa_state(val):
    """
    自定义格式
    :param val:
    :return:
    """
    if val is not "0" and val is not "1":
        print '\033[1;31m The parameter format is incorrect. \033[0m'
        msg = "The parameter format is incorrect."
        raise argparse.ArgumentTypeError(msg)
    return val


def node_count(val):
    """
    自定义格式
    :param val:
    :return:
    """
    vals = val.split(',')
    pattern = r"^[0-9]*$"
    for value in vals:
        if not re.match(pattern, value):
            print '\033[1;31m The parameter format is incorrect. \033[0m'
            msg = "The parameter format is incorrect."
            raise argparse.ArgumentTypeError(msg)
    return val


def kpa_type(val):
    """
    自定义格式
    :param val:
    :return:
    """
    if val != 'nginx' and val != 'mysql' and val != 'redis' and val != 'mq':
        print '\033[1;31m The parameter format is incorrect. \033[0m'
        msg = "The parameter format is incorrect."
        raise argparse.ArgumentTypeError(msg)
    return val


def parser_async_msg(subparsers):
    """
    rabbitmq消息队列模块
    :param subparsers:
    :return:
    """
    parser = subparsers.add_parser('async_msg')
    parser.add_argument(
        '-eh',
        default='127.0.0.1',
        required=True,
        type=perfect_square,
        help="Eureka ip address."
    )
    parser.add_argument(
        '-mh',
        default='127.0.0.1',
        type=perfect_square,
        help="Database ip address."
    )
    parser.add_argument(
        '-mq',
        default='127.0.0.1',
        type=perfect_square,
        help="Rabbitmq ip address."
    )
    parser.add_argument(
        '-ah',
        default='127.0.0.1',
        help="Eureka instance ip-address"
    )
    parser.add_argument(
        '-rh',
        default='127.0.0.1',
        type=perfect_square,
        help="Redis ip address."
    )

    parser.set_defaults(func=deploy_async_msg)


def parser_eureka(subparsers):
    """
    注册中心eureka模块
    :param subparsers:
    :return:
    """
    parser = subparsers.add_parser('eureka')
    parser.add_argument(
        '-eh',
        default='127.0.0.1',
        required=True,
        type=perfect_square,
        help="Eureka ip address."
    )
    parser.add_argument(
        '-ah',
        default='127.0.0.1',
        help="Eureka instance ip-address"
    )

    parser.set_defaults(func=deploy_eureka)


def parser_hosts(subparsers):
    """
    修改hosts
    :param subparsers:
    :return:
    """
    parser = subparsers.add_parser('hosts')
    parser.add_argument(
        '-ih',
        default='127.0.0.1',
        required=True,
        type=check_hosts,
        help="Insert ip and hostname."
    )

    parser.set_defaults(func=deploy_hosts)


def parser_keepalived(subparsers):
    """
    修改keepalived配置
    :param subparsers:
    :return:
    """
    parser = subparsers.add_parser('keepalived')
    parser.add_argument(
        '-ks',
        default='0',
        required=True,
        type=kpa_state,
        help="keepalived state."
    )
    parser.add_argument(
        '-ki',
        default='network',
        required=True,
        type=str,
        help="keepalived network interface."
    )
    parser.add_argument(
        '-kv',
        default='0.0.0.0',
        required=True,
        type=perfect_square,
        help="keepalived virtual ip address."
    )
    parser.add_argument(
        '-ha',
        default='1',
        # required=True,
        type=kpa_type,
        help="Keepalived high availability."
    )
    parser.add_argument(
        '-ms',
        choices=[8, 16, 24, 32],
        type=int,
        default=24,
        help="ip address mask, container values are 8, 16, 24, 32."
    )
    parser.add_argument(
        '-gw',
        default='0.0.0.0',
        # required=True,
        type=perfect_square,
        help="gateway."
    )

    parser.set_defaults(func=deploy_keepalived)


def parser_ms(subparsers):
    """
    主备部署（Master & Slave）
    :param subparsers:
    :return:
    """
    parser = subparsers.add_parser('ms')
    parser.add_argument(
        '-s',
        default='0',
        required=True,
        type=kpa_state,
        help="deploy state."
    )

    parser.add_argument(
        '-i',
        default='127.0.0.1',
        type=perfect_square,
        help="Master ip address."
    )

    parser.add_argument(
        '-hn',
        help="Host name."
    )

    parser.add_argument(
        '-c',
        default='3',
        type=node_count,
        help="Node count."
    )

    parser.add_argument(
        '-p',
        help="password."
    )

    parser.set_defaults(func=deploy_ms)


def parser_public(subparsers):
    """
    公共模块
    :param subparsers:
    :return:
    """
    parser = subparsers.add_parser('public')
    parser.add_argument(
        '-eh',
        default='127.0.0.1',
        required=True,
        type=perfect_square,
        help="Eureka ip address."
    )
    parser.add_argument(
        '-mh',
        default='127.0.0.1',
        type=perfect_square,
        help="Database ip address."
    )
    parser.add_argument(
        '-rh',
        default='127.0.0.1',
        type=perfect_square,
        help="Redis ip address."
    )
    parser.add_argument(
        '-mq',
        default='127.0.0.1',
        type=perfect_square,
        help="Rabbitmq ip address."
    )
    parser.add_argument(
        '-ah',
        default='127.0.0.1',
        help="Eureka instance ip-address"
    )

    parser.set_defaults(func=deploy_public)


def parser_task(subparsers):
    """
    任务微服务模块
    :param subparsers:
    :return:
    """
    parser = subparsers.add_parser('task')
    parser.add_argument(
        '-eh',
        default='127.0.0.1',
        required=True,
        type=perfect_square,
        help="Eureka ip address."
    )
    parser.add_argument(
        '-mh',
        default='127.0.0.1',
        type=perfect_square,
        help="Database ip address."
    )
    parser.add_argument(
        '-rh',
        default='127.0.0.1',
        type=perfect_square,
        help="Redis ip address."
    )
    parser.add_argument(
        '-mq',
        default='127.0.0.1',
        type=perfect_square,
        help="Rabbitmq ip address."
    )
    parser.add_argument(
        '-ah',
        default='127.0.0.1',
        help="Eureka instance ip-address"
    )

    parser.set_defaults(func=deploy_task)


def parser_game(subparsers):
    """
    云游戏模块
    :param subparsers:
    :return:
    """
    parser = subparsers.add_parser('game')
    parser.add_argument(
        '-eh',
        default='127.0.0.1',
        required=True,
        type=perfect_square,
        help="Eureka ip address."
    )
    parser.add_argument(
        '-mh',
        default='127.0.0.1',
        type=perfect_square,
        help="Database ip address."
    )
    parser.add_argument(
        '-rh',
        default='127.0.0.1',
        type=perfect_square,
        help="Redis ip address."
    )
    parser.add_argument(
        '-mq',
        default='127.0.0.1',
        type=perfect_square,
        help="Rabbitmq ip address."
    )
    parser.add_argument(
        '-th',
        default='127.0.0.1',
        type=perfect_square,
        help="fastdfs tracker ip-address"
    )
    parser.add_argument(
        '-ah',
        default='127.0.0.1',
        help="Eureka instance ip-address"
    )

    parser.set_defaults(func=deploy_game)


def parser_storage(subparsers):
    """
    超分模块
    :param subparsers:
    :return:
    """
    parser = subparsers.add_parser('storage')
    parser.add_argument(
        '-eh',
        default='127.0.0.1',
        required=True,
        type=perfect_square,
        help="Eureka ip address."
    )
    parser.add_argument(
        '-mh',
        default='127.0.0.1',
        type=perfect_square,
        help="Database ip address."
    )
    parser.add_argument(
        '-rh',
        default='127.0.0.1',
        type=perfect_square,
        help="Redis ip address."
    )
    parser.add_argument(
        '-mq',
        default='127.0.0.1',
        type=perfect_square,
        help="Rabbitmq ip address."
    )
    parser.add_argument(
        '-ah',
        default='127.0.0.1',
        help="Eureka instance ip-address"
    )

    parser.add_argument(
        '-gi',
        default='127.0.0.1',
        type=perfect_square,
        help="gateway ip-address"
    )

    parser.add_argument(
        '-gp',
        default='80',
        help="gateway port-address"
    )

    parser.add_argument(
        '-p',
        default='',
        help="vcfs path"
    )

    parser.set_defaults(func=deploy_storage)


def parser_game_wsi(subparsers):
    """
    云游戏websocket模块
    :param subparsers:
    :return:
    """
    parser = subparsers.add_parser('game_wsi')
    parser.add_argument(
        '-eh',
        default='127.0.0.1',
        required=True,
        type=perfect_square,
        help="Eureka ip address."
    )
    parser.add_argument(
        '-rh',
        default='127.0.0.1',
        type=perfect_square,
        help="Redis ip address."
    )
    parser.add_argument(
        '-ah',
        default='127.0.0.1',
        help="Eureka instance ip-address"
    )
    parser.add_argument(
        '-mq',
        default='127.0.0.1',
        help='Rabbitmq ip address.'
    )


    parser.set_defaults(func=deploy_game_wsi)


def parser_push(subparsers):
    """
    推送模块
    :param subparsers:
    :return:
    """
    parser = subparsers.add_parser('push')
    parser.add_argument(
        '-eh',
        default='127.0.0.1',
        required=True,
        type=perfect_square,
        help="Eureka ip address."
    )
    parser.add_argument(
        '-ah',
        default='127.0.0.1',
        help="Eureka instance ip-address"
    )
    parser.add_argument(
        '-rh',
        default='127.0.0.1',
        type=perfect_square,
        help="Redis ip address."
    )
    parser.set_defaults(func=deploy_push)


def parser_user(subparsers):
    """
    用户模块
    :param subparsers:
    :return:
    """
    parser = subparsers.add_parser('user')
    parser.add_argument(
        '-eh',
        default='127.0.0.1',
        required=True,
        type=perfect_square,
        help="Eureka ip address."
    )
    parser.add_argument(
        '-mh',
        default='127.0.0.1',
        type=perfect_square,
        help="Database ip address."
    )
    parser.add_argument(
        '-rh',
        default='127.0.0.1',
        type=perfect_square,
        help="Redis ip address."
    )
    parser.add_argument(
        '-mq',
        default='127.0.0.1',
        type=perfect_square,
        help="Rabbitmq ip address."
    )
    parser.add_argument(
        '-ah',
        default='127.0.0.1',
        help="Eureka instance ip-address"
    )

    parser.set_defaults(func=deploy_user)


def parser_upgrade(subparsers):
    """
    升级微服务
    :param subparsers:
    :return:
    """
    parser = subparsers.add_parser('upgrade')
    parser.add_argument(
        '-eh',
        default='127.0.0.1',
        required=True,
        type=perfect_square,
        help="Eureka ip address."
    )
    parser.add_argument(
        '-mh',
        default='127.0.0.1',
        type=perfect_square,
        help="Database ip address."
    )
    parser.add_argument(
        '-rh',
        default='127.0.0.1',
        type=perfect_square,
        help="Redis ip address."
    )
    parser.add_argument(
        '-mq',
        default='127.0.0.1',
        type=perfect_square,
        help="Rabbitmq ip address."
    )
    parser.add_argument(
        '-th',
        default='127.0.0.1',
        type=perfect_square,
        help="fastdfs tracker ip-address"
    )
    parser.add_argument(
        '-ah',
        default='127.0.0.1',
        help="Eureka instance ip-address"
    )

    parser.set_defaults(func=deploy_upgrade)


def parser_bbs(subparsers):
    """
    论坛服务
    :param subparsers:
    :return:
    """
    parser = subparsers.add_parser('bbs')
    parser.add_argument(
        '-mh',
        default='127.0.0.1',
        type=perfect_square,
        help="Database ip address."
    )
    parser.add_argument(
        '-s',
        default='127.0.0.1',
        # type=perfect_square,
        help="Community server address, default 127.0.0.1."
    )

    parser.add_argument(
        '-p',
        default=8021,
        type=int,
        help="Server port, default 8021."
    )

    parser.set_defaults(func=deploy_bbs)


def parser_wsi(subparsers):
    """
    webSocket模块
    :param subparsers:
    :return:
    """
    parser = subparsers.add_parser('wsi')
    parser.add_argument(
        '-eh',
        default='127.0.0.1',
        required=True,
        type=perfect_square,
        help="Eureka ip address."
    )
    parser.add_argument(
        '-mh',
        default='127.0.0.1',
        type=perfect_square,
        help="Database ip address."
    )
    parser.add_argument(
        '-rh',
        default='127.0.0.1',
        type=perfect_square,
        help="Redis ip address."
    )
    parser.add_argument(
        '-ah',
        default='127.0.0.1',
        help="Eureka instance ip-address"
    )
    parser.add_argument(
        '-th',
        default='127.0.0.1',
        type=perfect_square,
        help="fastdfs tracker ip-address"
    )

    parser.set_defaults(func=deploy_wsi)


def parser_zuul(subparsers):
    """
    网关微服务模块
    :param subparsers:
    :return:
    """
    parser = subparsers.add_parser('zuul')
    parser.add_argument(
        '-eh',
        default='127.0.0.1',
        required=True,
        type=perfect_square,
        help="Eureka ip address."
    )
    parser.add_argument(
        '-ah',
        default='127.0.0.1',
        help="Eureka instance ip-address"
    )

    parser.set_defaults(func=deploy_zuul)


def parser_mysql(subparsers):
    """

    :param subparsers:
    :return:
    """
    parser = subparsers.add_parser('mysql')
    parser.add_argument(
        '-n',
        default=0,
        type=int,
        help="Mysql database number."
    )
    parser.add_argument(
        '-i',
        default='127.0.0.1',
        type=perfect_square,
        help="Mysql master node address,must be used with the -m parameter."
    )
    parser.add_argument(
        '-m',
        default='',
        help="MASTER_LOG_FILE:MASTER_LOG_POS ."
    )
    parser.add_argument(
        '-s',
        default=0,
        type=int,
        help="Check the slave status."
    )
    parser.add_argument(
        '-init',
        default=0,
        type=int,
        help="Initialize the database."
    )

    parser.set_defaults(func=deploy_mysql)


def parser_nginx(subparsers):
    """

    :param subparsers:
    :return:
    """
    parser = subparsers.add_parser('nginx')
    parser.add_argument(
        '-i',
        default='',
        required=True,
        help="The zuul service node is deployed, and multiple zuul service nodes are separated by ','."
    )
    parser.add_argument(
        '-ws',
        default='',
        required=True,
        help="The websocket service node is deployed, and multiple websocket service nodes are separated by ','."
    )
    parser.add_argument(
        '-f',
        default='',
        required=True,
        help="The file service node is deployed, and multiple file service nodes are separated by ','."
    )
    parser.add_argument(
        '-gws',
        default='',
        required=True,
        help="The game websocket service node is deployed, and multiple game websocket service nodes are separated by ','."
    )
    parser.add_argument(
        '-ins',
        default='',
        required=True,
        help="The insight service node is deployed, and multiple insight service nodes are separated by ','."
    )
    parser.add_argument(
        '-p',
        default='',
        required=True,
        help="The push service node is deployed, and multiple push service nodes are separated by ','."
    )
    parser.add_argument(
        '-up',
        default='',
        required=True,
        help="The upgrade service node is deployed, and multiple upgrade service nodes are separated by ','."
    )

    parser.add_argument(
        '-nac',
        default='',
        required=True,
        help="The nacos service node is deployed, and multiple nacos service nodes are separated by ','."
    )

    parser.set_defaults(func=deploy_nginx)


def parser_net(subparsers):
    """

    :param subparsers:
    :return:
    """
    parser = subparsers.add_parser('net')
    parser.add_argument(
        '-mh',
        default='',
        type=perfect_square,
        required=True,
        help="Database ip address"
    )
    parser.add_argument(
        '-ih',
        default='',
        type=perfect_square,
        required=True,
        help="Intranet ip address"
    )
    parser.add_argument(
        '-nh',
        default='',
        help="public ip address"
    )

    parser.set_defaults(func=deploy_net)


def parser_visit(subparsers):
    """

    :param subparsers:
    :return:
    """
    parser = subparsers.add_parser('visit')
    parser.add_argument(
        '-mh',
        default='',
        type=perfect_square,
        required=True,
        help="Database ip address"
    )
    parser.add_argument(
        '-vh',
        default='',
        type=perfect_square,
        required=True,
        help="virtualIp ip address"
    )

    parser.set_defaults(func=deploy_visit)


def parser_fastdfs(subparsers):
    """

    :param subparsers:
    :return:
    """
    parser = subparsers.add_parser('fastdfs')
    parser.add_argument(
        '-th',
        default='',
        type=perfect_square,
        required=True,
        help="tracker_server ip address"
    )
    parser.add_argument(
        '-ah',
        default='',
        type=perfect_square,
        required=True,
        help="allow_hosts ip address"
    )
    parser.add_argument(
        '-bh',
        default='0.0.0.0',
        help="bind_addr ip address"
    )

    parser.set_defaults(func=deploy_fastdfs)


def parser_insight(subparsers):
    """
    超分智能管理微服务模块
    :param subparsers:
    :return:
    """
    parser = subparsers.add_parser("insight")
    parser.add_argument(
        '-mh',
        default='127.0.0.1',
        type=perfect_square,
        help="Database ip address."
    )
    parser.add_argument(
        '-rh',
        default='127.0.0.1',
        type=perfect_square,
        help="Redis ip address."
    )
    parser.add_argument(
        '-ah',
        default='127.0.0.1',
        help="nginx ip address"
    )
    
    parser.set_defaults(func=deploy_insight)


def parser_upgrade_py(subparsers):
    """
    平台升级微服务模块
    :param subparsers:
    :return:
    """
    parser = subparsers.add_parser("upgrade_py")
    parser.add_argument(
        '-mh',
        default='127.0.0.1',
        type=perfect_square,
        help="Database ip address."
    )
    parser.add_argument(
        '-rh',
        default='127.0.0.1',
        type=perfect_square,
        help="Redis ip address."
    )
    parser.add_argument(
        '-ah',
        default='127.0.0.1',
        help="node ip address"
    )
    parser.set_defaults(func=deploy_upgrade_py)


def parser_nacos(subparsers):
    """
    nacos服务模块
    :param subparsers:
    :return:
    """
    parser = subparsers.add_parser("nacos")
    parser.add_argument(
        '-init',
        default=0,
        type=int,
        help="Initialize the database."
    )

    parser.add_argument(
        '-i',
        default='127.0.0.1',
        #required=True,
        type=str,
        help="host ip."
    )

    parser.add_argument(
        '-ct',
        default='127.0.0.1',
        #required=True,
        type=str,
        help="cluster ip and port."
    )

    parser.add_argument(
        '-m',
        default=0,
        type=int,
        help="mode one or cluster."
    )
    parser.set_defaults(func=deploy_nacos)


def parser_para():
    """
    解析命令行参数
    :return:
    """
    parser = argparse.ArgumentParser(
        description='vCloud web management platform deployment.'
    )
    parser.add_argument(
        '-v', '--version',
        action='version',
        version='{version}'.format(version=VERSION),
        help='Get the current installed version.'
    )

    subparsers = parser.add_subparsers()

    # 添加ip和对应主机名
    parser_hosts(subparsers)
    # 部署keepalived配置
    parser_keepalived(subparsers)
    # mysql主主同步配置
    parser_mysql(subparsers)
    # 部署eureka注册中心服务节点
    parser_eureka(subparsers)
    # 部署rabbitmq服务节点
    parser_async_msg(subparsers)
    # 部署公共的管理微服务节点
    parser_public(subparsers)
    # 部署任务管理微服务节点
    parser_task(subparsers)
    # 部署用户管理微服务节点
    parser_user(subparsers)
    # 部署升级微服务
    parser_upgrade(subparsers)
    # 部署论坛服务节点
    parser_bbs(subparsers)
    # 部署webSocket管理微服务节点
    parser_wsi(subparsers)
    # 部署网关微服务节点
    parser_zuul(subparsers)
    # 部署nginx，提供负载均衡
    parser_nginx(subparsers)
    # 部署主备模式
    parser_ms(subparsers)
    # 部署内网和公网对应关系
    parser_net(subparsers)
    # 部署nginx访问节点
    parser_visit(subparsers)
    # 部署文件系统集群
    parser_fastdfs(subparsers)
    # 部署云游戏微服务
    parser_game(subparsers)
    # 部署云游戏websocket微服务
    parser_game_wsi(subparsers)
    # 部署超分storage微服务
    parser_storage(subparsers)
    # 部署超分智能管理微服务
    parser_insight(subparsers)
    # 部署推送服务
    parser_push(subparsers)
    # 部署平台升级微服务
    parser_upgrade_py(subparsers)
    # 部署nacos服务
    parser_nacos(subparsers)

    args = parser.parse_args()
    args.func(args)


def main():
    parser_para()


if __name__ == "__main__":
    main()

